<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class appstoreController extends appRain_Base_Core
{
    const ITEM_PER_PATE = 12;
    public $name = 'appStore';
    public $dispatch =  Array( 

        'preDispatchExclude'=>array(),
        'postDispatchExclude'=>array());

    /**
     * This function run before each
     * Action Method
     */
    public function __preDispatch()
    {
        $this->page_title = App::Config()->setting('appstoresettings_title');
        $this->set("section_title",App::Config()->setting('appstoresettings_title'));
        
        $this->set("selected","store");
    }

    /**
     * Render Store product display page
     * - URL are customize by
     *   URI_Manager >> Page_Router
     */
    public function indexAction($action=null, $id=null, $page=1)
    { 
        /* Set page meta information */
        $this->staticPageNameToMetaInfo('store');

		//App::Component('appStore')->Helper('Data')->sendOrderMail(12);
		
		
        if($action == 'bycat') {
       	
            $products = App::InformationSet('product')
                ->paging(
                    "category LIKE '%{$id}%' ORDER BY entrydate DESC"
                );

            $this->set('products',$products);

            $this->page_title = App::CategorySet()->idToName($id);
            $this->set("section_title",App::CategorySet()->idToName($id,'short'));
            $this->set("catid",$id);
        }
        else if($action == 'byprod'){
           
            $product = App::InformationSet('product')
                ->findById($id);

            $this->page_title = App::CategorySet()->idToName($product['category']) . ' | ' . $product['title'];
            $this->set("section_title",App::CategorySet()->idToName($product['category']));

			$comments = App::Model('StoreComment')->findAll("productid={$id} AND status='Active'");
            $this->set('comments',$comments);
			
            $this->set('product',$product);
            $this->set("catid",$product['category']);
         
        }
        else {
            // Fetch all Featured Products
            $page = is_numeric($action) ? $action : 1;
            $products = App::InformationSet('product')
                ->findAll("isfeatured='Yes' and status='Active' ORDER BY entrydate DESC");
            $this->set('products',$products);
            $this->set("catid","");
        }
        
        $storeslides = App::InformationSet('storeslide')
            ->setPagination('No')
            ->findAllByStatus('Active');
        $this->set('storeslides',$storeslides);
        $this->set("action",$action);
        $this->set("id",$id);
    }

    private function itemperpage()
    {
        $itemperpage = App::Config()->siteInfo('appstoresettings_itemperpage',false);
        return ($itemperpage) ? $itemperpage : self::ITEM_PER_PATE;
    }

    /**
     * Function called by AJAX Request
     * Add/Update product to cart
     */
    public function add2qcartAction($pid=null,$qty=null)
    {
        if(!isset($this->get['ajax']))$this->redirect('/');

        $this->layout = 'empty';
		$this->data['Attribute'] = isset($this->data['Attribute']) ? $this->data['Attribute'] : array();
		
        try {
            App::Component('appStore')
                ->Helper('Data')
				->setAttribute($this->data['Attribute'])
                ->quickAdd($pid,$qty);

            $totalitem = App::Component('appStore')
                 ->Helper('Data')
                 ->getCartTotalItem();


            echo App::Load("Module/Cryptography")->jsonEncode(
                Array(
                    "_status" =>"Success",
                    "_hastocheckout"=>  App::Component('appStore')
                        ->Helper('Data')
                        ->isToCheckout(),
                        "totalitem"=>$totalitem,
                        "_message"=>$this->__('Cart updated successfully.')
                    )
            );

        }
        catch (AppException $e) {
            echo App::Load("Module/Cryptography")->jsonEncode(array( "_status" =>"Error", "_message"=>$e->getMessage()));
        }

    }

    /**
     * Render the checkout page
     */
    public function checkoutAction($action=null, $id=null)
    {
		//$this->layout = 'simple';
        // Set Meta information of the page
        $this->staticPageNameToMetaInfo('Checkout');

        // Attached all addons need for this section
        $this->addons = Array('datagrid');

        $cartinfo = App::Component('appStore')->Helper('Data')->getCartInfo();
        if(empty($cartinfo)) {
            $this->redirect("/store");
            exit;
        }

        // Remove Items from cart
        if($action=='removeitem') {
            App::Component('appStore')
                ->Helper('Data')
                ->removeItem($id);
            $this->redirect("/checkout");
            exit;
        }

        $this->set("section_title","Checkout");
    }
    /**
     * Function called by ajax Request to
     * Complete the Checkout process
     */
    public function completeCheckoutAction()
    {
        $this->layout = 'empty';
        if(empty($this->data)) {
            $this->redirect('/');
            exit;
        }
	
        try {
            // This call complete the Checkout process and also
            // execute payment processor. We used some magic
            // Functions to set data easily in inner blocks
            //
            // If any Function throw any Excepion from anywhere
            // then program control move in Catch Section without executing
            // rest part of the coding flow. This process
            // helps you to add as many payment processory you need
            // that controll the Checkout operation.
            // For help: www.apprain.com/ticket
            App::Component('appStore')->Helper('Data')
               // This is a magic method to set post data . Data can be
               // retrived by $this->getCheckoutPostData(). This function
               // return object of own class to mantain the chain of other call.
               ->setCheckoutPostData($this->data)
               ->organiseResource()
               ->orderValidation()
               // Start checkout Process and execute payment processor. This funtion throw
               // exception for any Invalid Result and stop all further execution
               ->StartCheckoutProcess()
               // Change the order status changed to PAID as no exception thrown from previouse
               // function.
               ->ChnageOrderStatus()
               // Clear cart SESSION.
               ->clearcart();

            // Return to Payment Success page
            echo App::Load("Module/Cryptography")->jsonEncode(array("_status" =>"Redirect","_location"=>$this->baseUrl("/payment-success")));
        }
        catch (AppException $e) {
            echo App::Load("Module/Cryptography")->jsonEncode(array( "_status" =>"Error", "_message"=>$e->getMessage()));
        }
    }

    /**
     * Display Order status pages
     */
    public function statusmessageAction($status=null)
    {
        if(!isset($status)) {
            $this->redirect("/");
            exit;
		}

        $page_content = $this->staticPageNameToMetaInfo($status);
        $this->set( 'page_content' ,$page_content );
        $this->set("section_title",$this->__("Payment Process"));
        $this->set("selected","store");
		
		$products = App::InformationSet('product')->findAll("isfeatured='Yes' and status='Active' ORDER BY entrydate DESC");
        $this->set('products',$products);			
    }

	
	
	public function getStateBoxAction($type=null,$code=null){
		$this->layout = 'empty';
		
		App::Session()->Write('shipping_country_code',$code);
		
		$data = array(
			'statebox'=>App::Component('appstore')->helper('Checkout')->getStateBox($code,"data[" . ucfirst($type) . "][state]",null,array("class"=>"input check_notempty")),
			'chckoutsummaryhtml' => App::Component('appstore')->helper('Checkout')->getChckoutSummaryHtml()
		);
		
		echo App::Module('Cryptography')->jsonEncode($data);
	}
	
	public function submitdiscountcodeAction($code=null){
		$this->layout = 'empty';	
		try{
			
			App::Component('appstore')->helper('Checkout')->executeCouponCode($code);		
			throw new AppException('Success');
		}
        catch (AppException $e) {
			echo App::Module('Cryptography')
				->jsonEncode(
				array(
					'response'=> $e->getMessage(),
					'chckoutsummaryhtml' => App::Component('appstore')->helper('Checkout')->getChckoutSummaryHtml($code)
				)
			);
        }
	}
			
	public function checkAttributeForValueAction($id=null,$requestkey=null){
		$this->layout ='empty';
		$Attributes = $this->data['Attribute'];
		
		$product = App::InformationSet('product')->findAllByAttributegroup($id);
		foreach($product['data'] as $row){
			$attributevalues = unserialize($row['attributevalue']);
			$flag = true;
			foreach($Attributes as $key=>$value){
				if(isset($attributevalues[$key])){
					$checkData = (is_array($attributevalues[$key]['value'])) ? $attributevalues[$key]['value'] : array($attributevalues[$key]['value']);
					if(!in_array($value,$checkData)){
						$flag = false;
					}
				}
			}
			
			if($flag){
				echo  
				App::Module('Cryptography')
					->jsonEncode(
						array(
							'status'=>'Success',
							'id'=>$row['id'],
							'price'=>App::Component('Appstore')->Helper('Common')->getPricebox($row)
						)
					);
				exit;
			}
		}		
		
		echo App::Module('Cryptography')
			->jsonEncode(
				array(
					'status'=>'Faield',
					'suggession' => App::Component('Appstore')->Helper('Common')->getAttributeSuggession($requestkey,$Attributes,$id) 
				)
			);
	}
	
	public function customer_reviewAction($id=null){
		if(empty($this->data)){
			$this->redirect("/");
		}
		
        // Set Empty Layout
        $this->layout = 'empty';

        // This is an simple example of Capture response by AppException Handaler
        // Hope you will like it
        // AJAX SUBMIT Helper capture response in JSON Formate
        // See Referance in Manual section from appRain official site
        try {
            $capacha = App::Module('Session')->read('capacha');

            if($capacha['storecommet'] != $this->data['StoreComment']['capacha']){
                throw new AppException($this->__("Please fillin the text display left side image correctly."));
            }
            // Save Comments
            // Please apply more logic if you needed
            $this->data['StoreComment']['productid'] = $id;
            $this->data['StoreComment']['status'] = 'Inactive';
            $this->data['StoreComment']['ip'] = App::Config()->getServerInfo('REMOTE_ADDR');			
            $this->data['StoreComment']['dated'] = App::Helper('Date')->getDate("Y-m-d H:i:s");
			
            $obj = App::Model('StoreComment')->Save($this->data);
			
            // Send Email notification using
            // Template Manager Helper
            App::Helper('EmailTemplate')
				->setParameters(
					Array(
						'Name'=>$this->data['StoreComment']['name'],
						'Comment'=>$this->data['StoreComment']['comment'],
						'EmailAddress'=>$this->data['StoreComment']['email']
					)
				)
                ->prepare('StoreComment',true);

            $status = 'Success';
            throw new AppException($this->__("Thank you, Your comment is waiting for approval."));
        }
        catch (AppException $e){
            // Catch exceptions and display message
            // in JSON format using Cryptography Helper
			$status = (isset($status) ? $status : 'Error');
            echo App::Load("Module/Cryptography")
				->jsonEncode(
					array(
						"_status" =>(isset($status) ? $status : 'Error'),
						"_message"=> App::Html()->getTag('span',array('class'=>strtolower($status)),$e->getMessage())
					)
				);
        }
	}
	
	public function downloadAction($key=null){
		
		$this->layout = 'empty';
		if(!isset($key)){
			$this->redirect();
		}
		
		$KeyDecrypted = base64_decode($key);
		$KeyDecrypted = explode('O',$KeyDecrypted);
		
		if(count($KeyDecrypted) != 2){
			$this->redirect();
		}
		
		$Order = App::Model('Order')->findById($KeyDecrypted[0]);
		$Product = App::InformationSet('Product')->findById($KeyDecrypted[1]);
		if(empty($Order) OR empty($Product)){
			$this->redirect();
		}		
		
		$time = time()-strtotime($Order['orderdate']);
		$days = round($time/(60*60*24));
		if($days > 7 ){
			$this->redirect();
		}
		$Product['downloadfilepath'] = 'sdfsdf\ssdfsdf/sdfsdf';
		$chkStr = strstr("/",$Product['downloadfilepath']);
		pre($chkStr);
		//if(count($chkStr))
		
		
	}
}
